<template>
    <div>
        <NavBar title="登录" />
        <img class="logo" src="@/assets/imgs/logo-myzx.png" alt="">
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="phone" name="phone" label="手机号码" placeholder="手机号码" :rules="[
                    { required: true, message: '请填写手机号码' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请填写合法的手机号码' }
                ]" />
                <div class="msgcode">
                    <van-field v-model="msgCode" name="msgCode" label="验证码" placeholder="验证码"
                        :rules="[{ required: true, message: '请填写验证码' }]" />
                    <van-button @click="sendMsg" v-show="btnType == 1" native-type="button"
                        size="mini">发送验证码</van-button>
                    <van-button v-show="btnType == 2" native-type="button" size="mini">{{ current.seconds
                        }}s之后重新发送</van-button>
                </div>
            </van-cell-group>

            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>

    </div>
</template>

<script lang="ts" setup>

import { useCountDown } from '@vant/use';
import { ref } from 'vue';
import { getMsgCode, login } from '@/utils/api';
import { showToast } from 'vant';
import { useRouter } from 'vue-router';
const router = useRouter();
// 1显示发送按钮, 2显示倒计时按钮
const btnType = ref<number>(1);
const countDown = useCountDown({
    // 倒计时60s
    time: 10 * 1000,
    // 倒计时结束的回调函数
    onFinish() {
        // 重置倒计时
        countDown.reset();
        // 显示发送按钮
        btnType.value = 1;
    }
});
const current = countDown.current;

const phone = ref('');
const msgCode = ref('');
// 用户类型 patient: 患者  staff：医生
const type = ref('');
const phonePattern = /^1[3-9]\d{9}$/
const sendMsg = async () => {
    if (!phonePattern.test(phone.value)) {
        return showToast('请输入合法的手机号码')
    }
    btnType.value = 2;
    countDown.start();
    // 请求验证码
    const { data: { code, msg, data } } = await getMsgCode(phone.value);
    if (code === 200) {
        msgCode.value = data;
    } else {
        showToast(msg)
    }

}
const onSubmit = async (values: any) => {
    console.log('submit', values);
    const { data: { code, msg, data } } = await login(values);
    if (code == 200) {
        localStorage.setItem('userLoginInfo', JSON.stringify(data));
        router.replace('/my');
        return;
    }
    showToast(msg)
};
</script>

<style scoped lang="scss">
.logo {
    width: 60%;
    display: block;
    margin: 40px auto;
}

.msgcode {
    position: relative;
}

.msgcode button {
    position: absolute;
    right: 10px;
    top: 10px;
}
</style>